package com.xiaotu.aop;

import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.xiaotu.constant.CommonConstants;
import com.xiaotu.exception.LoginException;
import com.xiaotu.util.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * @author zhangxiao
 * @create 2021-01-17 14:14
 */
@Aspect
@Component
@Slf4j
public class ResponseAspect {

    //抽取公共的切入点表达式
    //1.本类引用
    //2.其他的切面引用
    //@Pointcut("execution(public * com.wzzx.login.LoginController.*(..))")
    //@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    @Pointcut("execution(public * com.xiaotu..*Controller.*(..))")
    public void pointCut() {

    }

    public static final Map res = new HashMap();

    @Around("pointCut()")
    public R responseStatus(ProceedingJoinPoint joinPoint) {
        try {
            Object proceed = joinPoint.proceed();
            if (ObjectUtil.isNull(proceed))
                proceed = res;
            return R.ok(proceed);
        } catch (TokenExpiredException e) {
            log.error(e.getMessage(), e);
            return R.failed(CommonConstants.TOKEN_EXPIRED, e.getMessage());
        } catch (LoginException e) {
            log.error(e.getMessage(), e);
            return R.failed(res, e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.failed(res, e.getMessage());
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return R.failed(res, e.getMessage());
        }
    }

}
